import sys
import os.path
import datetime
import inspect


levels=['error','warning','info','debug']

class Level():
    def __init__(self):
        self.ERROR=0
        self.WARNING=1
        self.INFO=2
        self.DEBUG=3
    
level=Level()

class Log():
    def __init__(self,
                 filename=None,
                 stderr=True,
                 syslog=False,
                 stdout=False):
        self.stderr=stderr
        self.syslog=syslog
        self.stdout=stdout
        self.filename=filename
        self.loglevel=3
        if self.filename:
            self.__logfile=open(self.filename,'a')
        self.date_format='%c'
        self.__stderr=sys.stderr
        self.__stdout=sys.stdout
    def open(self, filename):
        self.filename=filename
        self.__logfile=open(self.filename,'a')
    def close(self):
        self.__logfile.close()
        self.filename=None
    def caller(self):
        filename=os.path.basename(inspect.stack()[2][1])
        linenum=inspect.stack()[2][2]
        method=inspect.stack()[2][3]
        return "%s: %s (%s)" % (filename, linenum, method)
    def write(self,msg,level=3,caller=None):
        datestamp=datetime.datetime.today().strftime(self.date_format)
        if not caller:
            caller=self.caller()
        #caller='fake caller'
        msg='[%s][%s] %s: %s\n' % (datestamp,levels[level],caller,msg)
        if level <= self.loglevel:
            if self.stderr:
                self.__stderr.write(msg)
            if self.stdout:
                self.__stderr.write(msg)
            if self.filename:
                self.__logfile.write(msg)
    def flush(self):
        if self.stderr:
            self.__stderr.flush()
        if self.stdout:
            self.__stdout.flush()
        if self.filename:
            self.__logfile.flush()

logfile=Log(stderr=True)
   
    
        
